package com.kpmg.datalake.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.kpmg.datalake.common.dynamicdatasource.DynamicDataSourceContextHolder;
import com.kpmg.datalake.common.enums.ResultCodeEnum;
import com.kpmg.datalake.common.utils.ContextHolderUtils;
import com.kpmg.datalake.common.vo.ServerResponse;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Session拦截器
 *
 * @author sail
 */
@Component
public class SessionInterceptor implements HandlerInterceptor {


  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)
      throws Exception {
    //session 拦截器使用判断超时返回ajax前台提示
    if (ContextHolderUtils.getLoginUser() == null) {
      try (OutputStream outputStream = response.getOutputStream()) {
        String outString = JSONObject.toJSONString(
            ServerResponse.serverResponse(ResultCodeEnum.CODE0002, null, null));
        outputStream.write(outString.getBytes());
      }
      return false;
    }
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse,
      Object o, ModelAndView modelAndView) {
    // do nothing
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse httpServletResponse,
      Object o, Exception e) {
    DynamicDataSourceContextHolder.clearDataSource();
  }

}
